package com.dong.bolt;

/**
 * @author dengxiudong
 * @Date 2024/10/12 上午9:48
 */

import com.alipay.sofa.rpc.config.ProviderConfig;
import com.alipay.sofa.rpc.config.ServerConfig;
import com.alipay.sofa.rpc.server.bolt.BoltServer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

@SpringBootApplication
public class TcpServerApplication implements CommandLineRunner
{

    public static void main(String[] args) {
        SpringApplication.run(TcpServerApplication.class, args);
    }

    @Override
    public void run(String... args) {
        ServerConfig config = new ServerConfig();
        config.setProtocol("bolt");
        config.setPort(8080);
        config.setDaemon(true);
        config.setQueues(100);
        config.setCoreThreads(20);
        config.setMaxThreads(100);
        config.setHost("0.0.0.0");
        config.setSerialization("json");


        // 创建 Bolt 服务器，监听指定端口
        BoltServer server = new BoltServer();
        server.init(config);
        // ProviderConfig<HelloService> providerConfig = new ProviderConfig<>();
        // server.registerProcessor(providerConfig,);

        // 启动服务器
        server.start();

        System.out.println("TCP 服务器已启动，正在监听端口 8080...");
    }

    private void handleClient(Socket clientSocket) {
        new Thread(() -> {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                 PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {

                String message;
                while ((message = in.readLine()) != null) {
                    System.out.println("收到消息: " + message);
                    String response = "你发送的消息是: " + message;
                    out.println(response); // 发送响应给客户端
                }
            } catch (IOException e) {
                System.out.println("处理客户端连接时发生错误: " + e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                    System.out.println("客户端断开连接: " + clientSocket.getRemoteSocketAddress());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}